﻿using System;
using System.Data;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using Pantry.Business;
using Pantry.Commons;
using Pantry.Entity;

namespace Pantry.Web.Users
{
    public partial class ServiceDetails : System.Web.UI.Page
    {
        private ServiceBus _serviceBus;
        private Service _service;
        private Funder _funder;
        private ContactBus _contactBus;
        private string _pageTitle;
        private FunderBus _funderBus;
        protected void Page_Load(object sender, EventArgs e)
        {
            _serviceBus = new ServiceBus();
            _funderBus = new FunderBus();
            ListContact.SendContactToPage += delegate(string contact)
            { 
                string[] contacts = contact.Split('$');
                HiddenFeildContactId.Value = contacts[0];
                TextBoxLeadContact.Text = contacts[1];
                HiddenFieldFundingContactDetail.Value = contacts[0];
                TextBoxFundingContactDetail.Text = contacts[1];
            };
            ServicePremise.AlertToParents += delegate(string a)
             {
                 CheckCondition(sender, e);
             };
            if (!IsPostBack)
            {
                LoadEditData();
            }
            Page.Title = _pageTitle;
        }

        #region Methods
        /// <summary>
        /// Fills the data to drop down list.
        /// </summary>
        protected void FillDataToDropDownList()
        {
            _serviceBus = new ServiceBus();
            // fill data to DropDownList SubType
            DropDownListSubType.DataSource = _serviceBus.SelectServiceSubType();
            DropDownListSubType.DataTextField = "Name";
            DropDownListSubType.DataValueField = "ID";
            DropDownListSubType.DataBind();
            // fill data to DropDownList ServiceAttendance
            DropDownListServiceAttendance.DataSource = _serviceBus.SelectServiceAttendance();
            DropDownListServiceAttendance.DataTextField = "Name";
            DropDownListServiceAttendance.DataValueField = "ID";
            DropDownListServiceAttendance.DataBind();
            // fill data to DropDownList ServiceAttendance
            DropDownListServiceAttendance.DataSource = _serviceBus.SelectServiceAttendance();
            DropDownListServiceAttendance.DataTextField = "Name";
            DropDownListServiceAttendance.DataValueField = "ID";
            DropDownListServiceAttendance.DataBind();
            // fill data to DropDownList ServiceType
            DropDownListServieType.DataSource = _serviceBus.SelectServiceType();
            DropDownListServieType.DataTextField = "Name";
            DropDownListServieType.DataValueField = "ID";
            DropDownListServieType.DataBind();
            // fill data to DropDownList ReferralProcess
            DropDownListReferralProcess.DataSource = _serviceBus.SelectReferralProcess();
            DropDownListReferralProcess.DataTextField = "Name";
            DropDownListReferralProcess.DataValueField = "ID";
            DropDownListReferralProcess.DataBind();
            //Programmes
            var dt5 = new ProgramBus().RetrieveAllData();
            DropDownListProgramme.DataSource = dt5;
            DropDownListProgramme.DataValueField = "ProgramId";
            DropDownListProgramme.DataTextField = "ProgramName";
            DropDownListProgramme.DataBind();
            // Service Benefits Criterion 
            var dt1 = new ServiceOrgBus().Select(37);
            CheckBoxListServiceBenefitsCriterion.DataSource = dt1;
            CheckBoxListServiceBenefitsCriterion.DataValueField = "ServiceID";
            CheckBoxListServiceBenefitsCriterion.DataTextField = "ServiceName";
            CheckBoxListServiceBenefitsCriterion.DataBind();
            // Service Barriers Criterion
            var dt2 = new ServiceOrgBus().Select(38);
            CheckBoxListServiceBarriersCriterion.DataSource = dt2;
            CheckBoxListServiceBarriersCriterion.DataValueField = "ServiceID";
            CheckBoxListServiceBarriersCriterion.DataTextField = "ServiceName";
            CheckBoxListServiceBarriersCriterion.DataBind();
            // Service Ethnicity Criterion
            var dt3 = new ServiceOrgBus().Select(39);
            CheckBoxListServiceEthnicityCriterion.DataSource = dt3;
            CheckBoxListServiceEthnicityCriterion.DataValueField = "ServiceID";
            CheckBoxListServiceEthnicityCriterion.DataTextField = "ServiceName";
            CheckBoxListServiceEthnicityCriterion.DataBind();
            // Service Disability Criterion
            var dt4 = new ServiceOrgBus().Select(40);
            CheckBoxListServiceDisabilityCriterion.DataSource = dt4;
            CheckBoxListServiceDisabilityCriterion.DataValueField = "ServiceID";
            CheckBoxListServiceDisabilityCriterion.DataTextField = "ServiceName";
            CheckBoxListServiceDisabilityCriterion.DataBind();
            // Service Personal Circumstances Criterion 
            var dt6 = new ServiceOrgBus().Select(41);
            CheckBoxListServicePersonalCircumstancesCriterion.DataSource = dt6;
            CheckBoxListServicePersonalCircumstancesCriterion.DataValueField = "ServiceID";
            CheckBoxListServicePersonalCircumstancesCriterion.DataTextField = "ServiceName";
            CheckBoxListServicePersonalCircumstancesCriterion.DataBind();
            // Other Service Participation Criterion
            var dt7 = new ServiceOrgBus().Select(42);
            CheckBoxListOtherServiceParticipationCriterion.DataSource = dt7;
            CheckBoxListOtherServiceParticipationCriterion.DataValueField = "ServiceID";
            CheckBoxListOtherServiceParticipationCriterion.DataTextField = "ServiceName";
            CheckBoxListOtherServiceParticipationCriterion.DataBind();
            // Client Support Process 
            var dt8 = new ServiceOrgBus().Select(43);
            CheckBoxListClientSupportProcess.DataSource = dt8;
            CheckBoxListClientSupportProcess.DataValueField = "ServiceID";
            CheckBoxListClientSupportProcess.DataTextField = "ServiceName";
            CheckBoxListClientSupportProcess.DataBind();
            // Intervention  
            var dt9 = new ServiceOrgBus().Select(44);
            CheckBoxListIntervention.DataSource = dt9;
            CheckBoxListIntervention.DataValueField = "ServiceID";
            CheckBoxListIntervention.DataTextField = "ServiceName";
            CheckBoxListIntervention.DataBind();
            // Client Journey   
            var dt10 = new ServiceOrgBus().Select(45);
            CheckBoxListClientJourney.DataSource = dt10;
            CheckBoxListClientJourney.DataValueField = "ServiceID";
            CheckBoxListClientJourney.DataTextField = "ServiceName";
            CheckBoxListClientJourney.DataBind();
            // Other Service  
            var dt11 = new ServiceOrgBus().Select(46);
            CheckBoxListOtherService.DataSource = dt11;
            CheckBoxListOtherService.DataValueField = "ServiceID";
            CheckBoxListOtherService.DataTextField = "ServiceName";
            CheckBoxListOtherService.DataBind();
            // Support Centres 
            var dt12 = new ServiceOrgBus().Select(47);
            CheckBoxListSupportCentres.DataSource = dt12;
            CheckBoxListSupportCentres.DataValueField = "ServiceID";
            CheckBoxListSupportCentres.DataTextField = "ServiceName";
            CheckBoxListSupportCentres.DataBind();
            // Client Outcome 
            var dt13 = new ServiceOrgBus().Select(48);
            CheckBoxListClientOutcome.DataSource = dt13;
            CheckBoxListClientOutcome.DataValueField = "ServiceID";
            CheckBoxListClientOutcome.DataTextField = "ServiceName";
            CheckBoxListClientOutcome.DataBind();
            // Target Client  
            var dt14 = new ServiceOrgBus().Select(49);
            CheckBoxListTargetClient.DataSource = dt14;
            CheckBoxListTargetClient.DataValueField = "ServiceID";
            CheckBoxListTargetClient.DataTextField = "ServiceName";
            CheckBoxListTargetClient.DataBind();
            // Accreditation  
            var dt15 = new ServiceOrgBus().Select(50);
            CheckBoxListAccreditation.DataSource = dt15;
            CheckBoxListAccreditation.DataValueField = "ServiceID";
            CheckBoxListAccreditation.DataTextField = "ServiceName";
            CheckBoxListAccreditation.DataBind();
            // Referral Sources   
            var dt16 = new ServiceOrgBus().Select(51);
            CheckBoxListReferralSources.DataSource = dt16;
            CheckBoxListReferralSources.DataValueField = "ServiceID";
            CheckBoxListReferralSources.DataTextField = "ServiceName";
            CheckBoxListReferralSources.DataBind();
            // Contract Outcome    
            var dt17 = new ServiceOrgBus().Select(52);
            CheckBoxListContractOutcome.DataSource = dt17;
            CheckBoxListContractOutcome.DataValueField = "ServiceID";
            CheckBoxListContractOutcome.DataTextField = "ServiceName";
            CheckBoxListContractOutcome.DataBind();
            // Contract Obligation  
            var dt18 = new ServiceOrgBus().Select(53);
            CheckBoxListContractObligation.DataSource = dt18;
            CheckBoxListContractObligation.DataValueField = "ServiceID";
            CheckBoxListContractObligation.DataTextField = "ServiceName";
            CheckBoxListContractObligation.DataBind();
			
        }

        /// <summary>
        /// Selects the funding source data.
        /// </summary>
        private void SelectFundingSourceData()
        {
            _funderBus = new FunderBus();
            DropDownListFundingSource.DataSource = _funderBus.SelectFundingSource();
            DropDownListFundingSource.DataTextField = "Name";
            DropDownListFundingSource.DataValueField = "ID";
            DropDownListFundingSource.DataBind();
        }

        /// <summary>
        /// Loads the edit data.
        /// </summary>
        protected void LoadEditData()
        {
            FillDataToDropDownList();
            SelectFundingSourceData();
            if ((Request.QueryString["action"] == "update" || Request.QueryString["action"] == "copy") && Request.QueryString["id"] != null)
            {
                _pageTitle = Request.QueryString["action"] == "update" ? "Update service" : "Copy service";
                try
                {
                    _service = _serviceBus.SelectServiceById(int.Parse(Request.QueryString["id"]));
                    _funder = _funderBus.SelectFunderById(int.Parse(Request.QueryString["id"]));
                    _contactBus = new ContactBus();
                    TextBoxServiceName.Text = Request.QueryString["action"] == "copy" ? "" : _service.Name;
                    TextBoxOrgannisationShortDescription.Text = _service.ShortDescription;
                    DropDownListSubType.SelectedValue = _service.ServiceSubType;
                    TextBoxLeadContact.Text = _contactBus.ManagerNameById(_service.ContactId);
                    HiddenFeildContactId.Value = _service.ContactId.ToString(CultureInfo.InvariantCulture);
                    TextBoxClientDescription.Text = _service.ClientDescription;
                    DropDownListServiceAttendance.SelectedValue = _service.ServiceAttendace;
                    TextBoxServiceStartExpected.Text = _service.ServiceStartExpected.ToString(CultureInfo.InvariantCulture).Substring(0,10);
                    TextBoxServiceStartDate.Text = _service.ServiceStart.ToString(CultureInfo.InvariantCulture).Substring(0, 10);
                    TextBoxServiceEndDate.Text = _service.ServiceEnd.ToString(CultureInfo.InvariantCulture);
                    CheckBoxServiceExtendable.Checked = _service.ServiceExtendable;
                    SpinnerYearExtendable.Text = (_service.ServiceExtendableMonth / 12).ToString(CultureInfo.InvariantCulture);
                    SpinnerMonthExtandable.Text = (_service.ServiceExtendableMonth % 12).ToString(CultureInfo.InvariantCulture);
                    TextAreaServiceFullDescription.Text = _service.FullDescription;
                    TextBoxDeptCode.Text = _service.DeptCode;
                    DropDownListServieType.SelectedValue = _service.ServiceType.ToString();
                    TextBoxServiceDescriptionDelivery.Text = _service.DescriptionDelivery;
                    TextBoxServiceContractCode.Text = _service.ServiceContractCode;
                    TextBoxServiceConstractValue.Text = _service.ServiceContractValue;
                    TextBoxContractStagedPayment.Checked = _service.ContractStagedPayment;
                    DropDownListReferralProcess.SelectedValue = _service.ReferralProcessMethod;
                    CheckBoxServiceTimeLimited.Checked = _service.ServiceTimeLimited;
                    SpinnerYearTimeLimited.Text = (_service.ServiceTimeLimitedMonth / 12).ToString(CultureInfo.InvariantCulture);
                    SpinnerMonthTimeLimited.Text = (_service.ServiceTimeLimitedMonth % 12).ToString(CultureInfo.InvariantCulture);
                    DropDownListProgramme.SelectedValue = _service.ProgrammeId.ToString(CultureInfo.InvariantCulture);
                    DropDownListParticipation.SelectedValue = _service.Participartion;
                    var id = int.Parse(Request.QueryString["id"]);
                    LoadEditCheckBoxData(CheckBoxListServiceBenefitsCriterion, id, 37);
                    LoadEditCheckBoxData(CheckBoxListServiceBarriersCriterion, id, 38);
                    LoadEditCheckBoxData(CheckBoxListServiceEthnicityCriterion, id, 39);
                    LoadEditCheckBoxData(CheckBoxListServiceDisabilityCriterion, id, 40);
                    LoadEditCheckBoxData(CheckBoxListServicePersonalCircumstancesCriterion, id, 41);
                    LoadEditCheckBoxData(CheckBoxListOtherServiceParticipationCriterion, id, 42);
                    LoadEditCheckBoxData(CheckBoxListClientSupportProcess, id, 43);
                    LoadEditCheckBoxData(CheckBoxListIntervention, id, 44);
                    LoadEditCheckBoxData(CheckBoxListClientJourney, id, 45);
                    LoadEditCheckBoxData(CheckBoxListOtherService, id, 46);
                    LoadEditCheckBoxData(CheckBoxListSupportCentres, id, 47);
                    LoadEditCheckBoxData(CheckBoxListClientOutcome, id, 48);
                    LoadEditCheckBoxData(CheckBoxListTargetClient, id, 49);
                    LoadEditCheckBoxData(CheckBoxListAccreditation, id, 50);
                    LoadEditCheckBoxData(CheckBoxListReferralSources, id, 51);
                    LoadEditCheckBoxData(CheckBoxListContractOutcome, id, 52);
                    LoadEditCheckBoxData(CheckBoxListContractObligation, id, 53);
                    // funding
                    if(_funder != null)
                    {
                        DropDownListFundingSource.SelectedValue = _funder.FundingSource;
                        TextBoxFundingContactDetail.Text = _contactBus.ManagerNameById(_service.ContactId);
                        HiddenFieldFundingContactDetail.Value = _funder.ContactId.ToString(CultureInfo.InvariantCulture);
                        TextBoxFundingAmount.Text = _funder.FundingAmount.ToString(CultureInfo.InvariantCulture);
                        TextBoxFundingStart.Text = _funder.FundingStart;
                        TextBoxFundingEnd.Text = _funder.FundingEnd;
                        TextBoxFundingNeeds.Text = _funder.FundingNeeds;
                        CheckBoxFundingContonuationNeeded.Checked = _funder.FundingContinuationNeed;
                        TextBoxFundingContinuationAmount.Text = _funder.FundingCotinuationAmount.ToString(CultureInfo.InvariantCulture);
                        TextBoxFundingContinuationDetails.Text = _funder.FundingContinuationDetail;
                        TextBoxFundraisingForText.Text = _funder.FundrasingForText;
                        TextBoxFundraisingWhy.Text = _funder.FundrasingWhy;
                        TextBoxFundraisingNeed.Text = _funder.FundrasingNeeds;
                        TextBoxFundraisingRequiredBy.Text = _funder.FundrasingRequireBy;
                        //CheckBoxFundingDraisingComplete.Checked = _funder.FundrasingComplete;
                        TextBoxFundraisingCompledtedDate.Text = _funder.FundrasingCompleteDate;
                        CheckBoxFundrasingDonor.Checked = _funder.FundrasingDonorAnonymous;
                        TextBoxFundraisingDonorAmount.Text = _funder.FundrasingDonorAmount;
                        TextBoxFundraisingDonation.Text = _funder.FundrasingDonationDate;
                        //CheckBoxFundraisingDonationIncremential.Checked = _funder.FundrasingDonationIncremental;
                    }
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                }
            }
            else
            {
                _pageTitle = "Create new service";
            }
        }
        #endregion

        #region Events
        protected void CheckBoxServiceExtendableCheckedChanged(object sender, EventArgs e)
        {
            SpinnerYearExtendable.Enabled = CheckBoxServiceExtendable.Checked;
            SpinnerMonthExtandable.Enabled = CheckBoxServiceExtendable.Checked;
        }

        protected void CheckBoxServiceTimeLimitedCheckedChanged(object sender, EventArgs e)
        {
            SpinnerYearTimeLimited.Enabled = CheckBoxServiceTimeLimited.Checked;
            SpinnerMonthTimeLimited.Enabled = CheckBoxServiceTimeLimited.Checked;
        }

        protected void CheckBoxFundingContonuationNeededChanged(object sender, EventArgs e)
        {
            TextBoxFundingContinuationAmount.Enabled = CheckBoxFundingContonuationNeeded.Checked;
            TextBoxFundingContinuationDetails.Enabled = CheckBoxFundingContonuationNeeded.Checked;
        }

        protected void CheckBoxFundingDraisingCompleteChanged(object sender, EventArgs e)
        {
            TextBoxFundraisingCompledtedDate.Enabled = CheckBoxFundingDraisingComplete.Checked;
        }

        protected void ButtonBackClick(object sender, EventArgs e)
        {
            Response.Redirect("ViewListService.aspx");
        }

        protected void SaveServiceClick(object sender, EventArgs e)
        {
            try
            {
                _serviceBus = new ServiceBus();
                _funderBus = new FunderBus();
                int limitMonth = 0;
                int limitYear = 0;
                int exMonth = 0;
                int exYear = 0;
                if (SpinnerMonthExtandable.Text.Length > 0)
                {
                    exMonth = int.Parse(SpinnerMonthExtandable.Text);
                }
                if (SpinnerYearExtendable.Text.Length > 0)
                {
                    exYear = int.Parse(SpinnerYearExtendable.Text);
                }
                if (SpinnerMonthTimeLimited.Text.Length > 0)
                {
                    limitMonth = int.Parse(SpinnerMonthTimeLimited.Text);
                }
                if (SpinnerMonthTimeLimited.Text.Length > 0)
                {
                    limitYear = int.Parse(SpinnerYearTimeLimited.Text);
                }
                int totalMonth = exMonth + (exYear * 12);
                int totalLimitMonth = limitMonth + (limitYear * 12);
                _service = new Service
                               {
                                   Name = TextBoxServiceName.Text,
                                   ShortDescription = TextBoxOrgannisationShortDescription.Text,
                                   ServiceSubType = DropDownListSubType.SelectedValue,
                                   ContactId = int.Parse(HiddenFeildContactId.Value),
                                   IsActive = 1,
                                   ClientDescription = TextBoxClientDescription.Text,
                                   ServiceAttendace = DropDownListServiceAttendance.SelectedValue,
                                   ServiceStartExpected = TextBoxServiceStartExpected.Text,
                                   ServiceStart = TextBoxServiceStartDate.Text,
                                   ServiceEnd = TextBoxServiceEndDate.Text,
                                   ServiceExtendable = CheckBoxServiceExtendable.Checked,
                                   ServiceExtendableMonth = totalMonth,
                                   FullDescription = TextAreaServiceFullDescription.Text,
                                   DeptCode = TextBoxDeptCode.Text,
                                   ServiceType = int.Parse(DropDownListServieType.SelectedValue),
                                   DescriptionDelivery = TextBoxServiceDescriptionDelivery.Text,
                                   ServiceContractCode = TextBoxServiceContractCode.Text,
                                   ServiceContractValue = TextBoxServiceConstractValue.Text,
                                   ContractStagedPayment = TextBoxContractStagedPayment.Checked,
                                   ReferralProcessMethod = DropDownListReferralProcess.SelectedValue,
                                   ServiceTimeLimited = CheckBoxServiceTimeLimited.Checked,
                                   ServiceTimeLimitedMonth = totalLimitMonth,
                                   ProgrammeId = int.Parse(DropDownListProgramme.SelectedValue),
                                   Participartion = DropDownListParticipation.SelectedValue
                                   
                };
                _funder = new Funder
                              {
                                  FundingSource = DropDownListFundingSource.SelectedValue,
                                  ContactId = int.Parse(HiddenFieldFundingContactDetail.Value),
                                  FundingAmount = float.Parse(TextBoxFundingAmount.Text),
                                  FundingStart = TextBoxFundingStart.Text,
                                  FundingEnd = TextBoxFundingEnd.Text,
                                  FundingNeeds = TextBoxFundingNeeds.Text,
                                  FundingContinuationNeed = CheckBoxFundingContonuationNeeded.Checked,
                                  FundingCotinuationAmount = float.Parse(TextBoxFundingContinuationAmount.Text),
                                  FundingContinuationDetail = TextBoxFundingContinuationDetails.Text,
                                  FundrasingForText = TextBoxFundraisingForText.Text,
                                  FundrasingWhy = TextBoxFundraisingWhy.Text,
                                  FundrasingNeeds = TextBoxFundraisingNeed.Text,
                                  FundrasingRequireBy = TextBoxFundraisingRequiredBy.Text,
                                  FundrasingComplete = CheckBoxFundingDraisingComplete.Checked,
                                  FundrasingCompleteDate = TextBoxFundraisingCompledtedDate.Text,
                                  FundrasingDonorAnonymous = CheckBoxFundrasingDonor.Checked,
                                  FundrasingDonorAmount = TextBoxFundraisingDonorAmount.Text,
                                  FundrasingDonationDate = TextBoxFundraisingDonation.Text,
                                  FundrasingDonationIncremental = CheckBoxFundraisingDonationIncremential.Checked
                              };
                if (Request.QueryString["action"] == "update")
                {

                    int id = int.Parse(Request.QueryString["id"]);
                    _service.Id = id;
                    if(_serviceBus.CheckUniqueForUpdate("Services","Name",TextBoxServiceName.Text,"ID",id))
                    {

                        bool result = _serviceBus.UpdateService(_service) > 0;
                        if (result)
                        {
                            UpdateDataFromCheckListBox(CheckBoxListServiceBenefitsCriterion, id, 37);
                            UpdateDataFromCheckListBox(CheckBoxListServiceBarriersCriterion, id, 38);
                            UpdateDataFromCheckListBox(CheckBoxListServiceEthnicityCriterion, id, 39);
                            UpdateDataFromCheckListBox(CheckBoxListServiceDisabilityCriterion, id, 40);
                            UpdateDataFromCheckListBox(CheckBoxListServicePersonalCircumstancesCriterion, id, 41);
                            UpdateDataFromCheckListBox(CheckBoxListOtherServiceParticipationCriterion, id, 42);
                            UpdateDataFromCheckListBox(CheckBoxListClientSupportProcess, id, 43);
                            UpdateDataFromCheckListBox(CheckBoxListIntervention, id, 44);
                            UpdateDataFromCheckListBox(CheckBoxListClientJourney, id, 45);
                            UpdateDataFromCheckListBox(CheckBoxListOtherService, id, 46);
                            UpdateDataFromCheckListBox(CheckBoxListSupportCentres, id, 47);
                            UpdateDataFromCheckListBox(CheckBoxListClientOutcome, id, 48);
                            UpdateDataFromCheckListBox(CheckBoxListTargetClient, id, 49);
                            UpdateDataFromCheckListBox(CheckBoxListAccreditation, id, 50);
                            UpdateDataFromCheckListBox(CheckBoxListReferralSources, id, 51);
                            UpdateDataFromCheckListBox(CheckBoxListContractOutcome, id, 52);
                            UpdateDataFromCheckListBox(CheckBoxListContractObligation, id, 53);
                            _funder.ServiceId = id;
                            _funderBus.UpdateFunder(_funder);
                        }
                        ScriptManager.RegisterStartupScript(this, GetType(), "", result
                                                                                  ? "showmessage('Update service successfully !','SUCCESS','','false');"
                                                                                   : "showmessage('Can't update service !','ERROR','','false');", true);
                    }
                    else
                    {
                        ScriptManager.RegisterStartupScript(this, GetType(), "",
                                                            "showmessage('Service Name is exits !','ERROR','','false');",
                                                            true);
                    }
                }
                else
                {
                    if(_serviceBus.CheckUniqueForAdd("Services","Name",TextBoxServiceName.Text))
                    {

                        bool result = _serviceBus.InsertService(_service) > 0;
                        if (result)
                        {
                            var serviceId = int.Parse(new ServiceBus().SelectServiceId(_service.Name).Rows[0]["ID"].ToString());
                            if (serviceId != 0)
                            {
                                UpdateDataFromCheckListBox(CheckBoxListServiceBenefitsCriterion, serviceId, 37);
                                UpdateDataFromCheckListBox(CheckBoxListServiceBarriersCriterion, serviceId, 38);
                                UpdateDataFromCheckListBox(CheckBoxListServiceEthnicityCriterion, serviceId, 39);
                                UpdateDataFromCheckListBox(CheckBoxListServiceDisabilityCriterion, serviceId, 40);
                                UpdateDataFromCheckListBox(CheckBoxListServicePersonalCircumstancesCriterion, serviceId, 41);
                                UpdateDataFromCheckListBox(CheckBoxListOtherServiceParticipationCriterion, serviceId, 42);
                                UpdateDataFromCheckListBox(CheckBoxListClientSupportProcess, serviceId, 43);
                                UpdateDataFromCheckListBox(CheckBoxListIntervention, serviceId, 44);
                                UpdateDataFromCheckListBox(CheckBoxListClientJourney, serviceId, 45);
                                UpdateDataFromCheckListBox(CheckBoxListOtherService, serviceId, 46);
                                UpdateDataFromCheckListBox(CheckBoxListSupportCentres, serviceId, 47);
                                UpdateDataFromCheckListBox(CheckBoxListClientOutcome, serviceId, 48);
                                UpdateDataFromCheckListBox(CheckBoxListTargetClient, serviceId, 49);
                                UpdateDataFromCheckListBox(CheckBoxListAccreditation, serviceId, 50);
                                UpdateDataFromCheckListBox(CheckBoxListReferralSources, serviceId, 51);
                                UpdateDataFromCheckListBox(CheckBoxListContractOutcome, serviceId, 52);
                                UpdateDataFromCheckListBox(CheckBoxListContractObligation, serviceId, 53);
                                _funder.ServiceId = serviceId;
                                _funderBus.InserFunder(_funder);
                            }

                        }
                        ScriptManager.RegisterStartupScript(this, GetType(), "", result
                                                                                  ? "showmessage('Create service successfully !','SUCCESS','ViewListService.aspx','true');"
                                                                                   : "showmessage('Can't create service !','ERROR','','false');", true);

                    }
                    else
                    {
                        ScriptManager.RegisterStartupScript(this, GetType(), "",
                                                            "showmessage('Service Name is exits !','ERROR','','false');",
                                                            true);
                    }
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        protected void CheckCondition(object sender, EventArgs e)
        {
            try
            {
                SpinnerYearExtendable.Enabled = CheckBoxServiceExtendable.Checked;
                SpinnerMonthExtandable.Enabled = CheckBoxServiceExtendable.Checked;

                var startDate = new DateTime(1900,1,1);
                var endDate = new DateTime(9999,12,31);
                if(TextBoxServiceStartDate.Text.Length >0)
                {
                    startDate = DateTime.Parse(TextBoxServiceStartDate.Text);
                }
                if(TextBoxServiceEndDate.Text.Length >0)
                {
                    endDate = DateTime.Parse(TextBoxServiceEndDate.Text);
                }
               //DateTime extendDate = DateTime.Parse(TextBoxServiceStartExpected.Text);
                DateTime now = DateTime.Now;
                int addDate = int.Parse(SpinnerMonthExtandable.Text) + int.Parse(SpinnerYearTimeLimited.Text);
                int checkPass = (now - startDate).Days;
                int checkFuture = CheckBoxServiceExtendable.Checked ? ((endDate - now).Days + addDate*30) : (endDate - now).Days;

                if(checkPass>=0 && checkFuture >=0)
                {
                    CheckBoxServiceActive.Checked = true;
                }
                else
                {
                    CheckBoxServiceActive.Checked = false;
                }

            }
            catch (Exception ex)
            {
                //Response.Write(ex.Message);
            }
        }
        private static void UpdateDataFromCheckListBox(ListControl checkBoxList, int serviceId, int parentId)
        {
            var serviceRelateBus = new ServiceRelateBus();
            var serviceRelate = new ServiceRelate
            {
                ServiceId = serviceId,
                ServiceOrgParentId = parentId
            };
            for (var i = 0; i < checkBoxList.Items.Count; i++)
            {
                if (checkBoxList.Items[i].Selected)
                {
                    serviceRelate.ServiceOrgId = int.Parse(checkBoxList.Items[i].Value);
                    serviceRelate.IsActive = true;
                    if (serviceRelateBus.IsExist(serviceRelate))
                    {
                        serviceRelateBus.Update(serviceRelate);
                    }
                    else
                    {
                        serviceRelateBus.Insert(serviceRelate);
                    }
                }
                else
                {
                    serviceRelate.ServiceOrgId = int.Parse(checkBoxList.Items[i].Value);
                    serviceRelate.IsActive = false;
                    if (serviceRelateBus.IsExist(serviceRelate))
                    {
                        serviceRelateBus.Update(serviceRelate);
                    }
                    else
                    {
                        serviceRelateBus.Insert(serviceRelate);
                    }
                }

            }
        }
        private static void LoadEditCheckBoxData(ListControl checkBoxList, int serviceId, int parentId)
        {
            var listValue = new ServiceRelateBus().Select(parentId, serviceId);
            foreach (DataRow dr in listValue.Rows)
            {
                foreach (ListItem listItem in checkBoxList.Items)
                {
                    if (listItem.Value == dr["ServiceOrgId"].ToString())
                    {
                        listItem.Selected = Boolean.Parse(dr["IsActive"].ToString());
                    }
                }
            }
        }

        protected void MarkSeviceInActive(object sender,EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(Request.QueryString["id"]))
                {
                    int serviceId = int.Parse(Request.QueryString["id"], CultureInfo.CurrentCulture);
                    _serviceBus = new ServiceBus();
                    bool result = _serviceBus.MarkActivated(false, serviceId);
                    ScriptManager.RegisterStartupScript(UpdatePanel1, GetType(), "MyKey",
                                                                           result
                                                                               ? "showmessage('Successfully !','SUCCESS','','false');"
                                                                               : "showmessage('Failed! !','ERROR','','false');",
                                                                           true);
                }
            }
            catch (ArgumentNullException exception)
            {
                ExceptionHandler.WriteErrorLog(exception);
            }
            catch (ArgumentException exception)
            {
                ExceptionHandler.WriteErrorLog(exception);
            }
            catch (FormatException exception)
            {
                ExceptionHandler.WriteErrorLog(exception);
            }
            catch (OverflowException exception)
            {
                ExceptionHandler.WriteErrorLog(exception);
            }
        }
        #endregion
    }
}
